package com.module.recall.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.util.Page;
import base.util.StringUtil;
import base.util.Tools;

import com.module.antiFake.vo.AntiFakeScanHistory;
import com.module.antiFake.vo.AppAttr;
import com.module.codeBind.common.CodeBindConstant;
import com.module.organization.vo.EntBind;
import com.module.recall.util.AntiFakeBeanUtil;

public class AppAttrDao extends GenericHibernateDao<AppAttr, String> {
	private static Logger logger = Logger.getLogger(AppAttrDao.class);
	static AppAttrDao dao;

	AppAttrDao() {

	}

	public static AppAttrDao getInstance() {
		if (dao == null) {
			dao = new AppAttrDao();
		}
		return dao;
	}

	/**
	 * 分页查询所有
	 * 
	 * @param bean
	 *            码应用属性对象
	 * @param start
	 *            开始行
	 * @param limit
	 *            每一页的最大行数
	 * @return Page 分页对象
	 */
	@SuppressWarnings("unchecked")
	public Page toList(Session session, AppAttr bean, Integer start,
			Integer limit) {
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		String hql = " from AppAttr  where status !='D'";
		String contSql = "select count(*) from AppAttr  where status  !='D'";
		StringBuffer sb = new StringBuffer(hql);
		StringBuffer condition = new StringBuffer();
		if (!StringUtil.isNull(bean.getName())) {
			condition.append(" and name like '%" + bean.getName() + "%'");
		}
		if (!StringUtil.isNull(bean.getCodeAppId())) {
			condition.append(" and codeAppId = '" + bean.getCodeAppId() + "'");
		}
		sb.append(condition.append(" ORDER BY createTime desc"));
		Query query = session.createQuery(sb.toString());
		query.setFirstResult(start).setMaxResults(limit);
		Query totalQuery = session.createQuery(contSql + condition);
		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());
		page.setRows(query.list());
		return page;
	}

	/**
	 * 根据码应用编号获取码应用名称
	 * 
	 * @param appCode
	 *            码应用编号
	 * @return 码应用名称
	 */
	@SuppressWarnings("unchecked")
	public List<String> getAppName(Session session, String appid) {
		String selAppSql = "select c_codeApp_name from endw_codeapp where c_codeApp_id = '"
				+ appid + "'";
		return session.createSQLQuery(selAppSql).list();
	}

	/**
	 * 逻辑删除
	 * 
	 * @param obj
	 *            bean对象
	 * @return 返回成功或者失败
	 */
	public boolean delete(Session session, AppAttr obj) {

		boolean flag = false;
		try {
			String hql = "update AppAttr set updaterId = ?,updateTime=?,status =? where id in ("
					+ obj.getId() + ")";
			Query query = session.createQuery(hql);
			query.setParameter(0, obj.getUpdaterId());
			query.setParameter(1, new Date());
			query.setParameter(2, CUDEnum.D.toString());
			query.executeUpdate();
			flag = true;
			return flag;
		} catch (Exception e) {
			return flag;
		}
	}

	/**
	 * 根据应用查询属性
	 * 
	 * @param codeAppId
	 *            应用ID
	 * @return 属性结果集
	 */
	@SuppressWarnings("unchecked")
	public List<AppAttr> getAttrByApp(Session session, String codeAppId,
			String bindId) {
		List<AppAttr> res = null;// 将用于存放保存的结果集合
		if (Tools.isValid(bindId)) {

		} else {
			String appAttrHql = "from AppAttr where status !='D' and codeAppId = ?";
			res = session.createQuery(appAttrHql).setString(0, codeAppId)
					.list();
			List<AppAttr> valueres = new Vector<AppAttr>();
			for (AppAttr attr : res) {
				if (attr.getFieldType().equals("comboBox")) {
					attr.setAppAttrComboList(session.createQuery(
							"from AppAttrCombo as ac where ac.appAttrId='"
									+ attr.getId() + "'").list());
				}
				valueres.add(attr);
			}
		}
		return res;
	}

	/**
	 * 通过码信息查询出相应的应用属性;
	 * @param antiFakeScanHistory 
	 * 
	 * @param codeInfo
	 * @return
	 * @throws SQLException
	 */
	public AntiFakeBeanUtil findAttrsByCode(Connection conn,
			AntiFakeScanHistory antiFakeScanHistory, List<EntBind> appCodeList) throws SQLException {
		AntiFakeBeanUtil beanUtil = new AntiFakeBeanUtil();
		beanUtil.setAntiFakeScanHistory(antiFakeScanHistory);
		String appCodeStr = warpAppCodeList(appCodeList);
		String rollNum = antiFakeScanHistory.getRollNum();
		int seqNum = antiFakeScanHistory.getSequenceNum();
		Statement stmt = null;
		ResultSet rs = null;
		ResultSet rsBatch = null;
		List<AppAttr> result = new ArrayList<AppAttr>();
		try {
			String batchSql = "select batchCode.i_sales_area_id salesAreaId,  batchCode.c_batch_no batchNo,batchCode.i_batch_code_state batchCodeState, bindBatch.c_bind_id bindId,batchCode.c_product_id productId,batchCode.c_product_Name productName from endw_batch_code_item codeItem,endw_bind_batch_code "
					+ "bindBatch,endw_batch_code batchCode  where codeItem.c_volume_no='"
					+ rollNum
					+ "' and (codeItem.i_start_seq<="
					+ seqNum
					+ " and codeItem.i_end_seq>="
					+ seqNum
					+ ")"
					+ " and codeItem.c_batch_code_id=bindBatch.c_batch_code_id and batchCode.c_id=codeItem.c_batch_code_id AND batchCode.c_status!='D'";
			stmt = conn.createStatement();
			rsBatch = stmt.executeQuery(batchSql);
			if (rsBatch.next() && !StringUtil.isNull(appCodeStr)) {
				String productId = rsBatch.getString("productId");
				String productName = rsBatch.getString("productName");
				String batchId = rsBatch.getString("bindId");
				String batchNo = rsBatch.getString("batchNo");
				int salesAreaId = rsBatch.getInt("salesAreaId");
				beanUtil.getAntiFakeScanHistory().setProductId(productId);
				beanUtil.getAntiFakeScanHistory().setProductName(productName);
				beanUtil.getAntiFakeScanHistory().setBatchNo(batchNo);
				beanUtil.getAntiFakeScanHistory().setSalesAreaId(salesAreaId);
				beanUtil.getAntiFakeScanHistory().setBatchCodeState(rsBatch.getInt("batchCodeState"));
				final String sqlStr = "select attr.i_app_type appType,attr.c_appAttr_name attrName,attr.c_value attrValue from endw_appattr attr,endw_bind bind "
						+ "where (attr.c_field_type='"
						+ CodeBindConstant.BIND_ATTR_TYPE_TEXT
						+ "' or attr.c_field_type='"
						+ CodeBindConstant.BIND_ATTR_TYPE_COMBOBOX
						+ "') "
						+ "and bind.c_bind_id='"
						+ batchId
						+ "' and bind.c_code_app_id=attr.c_codeApp_id and  attr.c_codeApp_id in("
						+ appCodeStr + ") AND  attr.c_status!='D'";
				rs = stmt.executeQuery(sqlStr);
				while (rs.next()) {
					AppAttr appAttr = new AppAttr();
					appAttr.setAppName(rs.getString("attrName"));
					appAttr.setValue(rs.getString("attrValue"));
					appAttr.setAppType(rs.getInt("appType"));
					result.add(appAttr);
				}
			}
		} finally {
			close(stmt);
			close(rs);
			close(rsBatch);
		}
		beanUtil.setAppAttrList(result);
		return beanUtil;
	}

	/**
	 * 把应用列表的id转为以逗号分隔的字符串;
	 * @param appCodeList
	 * @return
	 */
	private String warpAppCodeList(List<EntBind> appCodeList) {
		StringBuffer sb = new StringBuffer();
		String split = "";
		for (EntBind bind : appCodeList) {
			sb.append(split);
			sb.append("'");
			sb.append(bind.getCodeAppId());
			sb.append("'");
			split = ",";
		}
		return sb.toString();
	}

}
